package priv.lhy.activity.notify;

import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.kafka.listener.MessageListener;
import org.springframework.stereotype.Service;
import priv.lhy.activity.dal.entity.ActDrawNum;
import priv.lhy.activity.dal.persistence.ActDrawNumMapper;
import priv.lhy.utils.JsonUtils;

/**
 * author : lihy
 * date : 2019/2/16 8:57
 * 用户注册监听
 */
@Service
public class RegistryListener implements MessageListener<Integer, String> {

    @Autowired
    ActDrawNumMapper actDrawNumMapper;

    /**
     * 用户注册后增加抽奖资格
     * @param integerStringConsumerRecord
     */
    @Override
    public void onMessage(ConsumerRecord<Integer, String> integerStringConsumerRecord) {
        UserBean userBean = null;
        try {
            String jsonStr = integerStringConsumerRecord.value();
            userBean = (UserBean) JsonUtils.json2Object(jsonStr, UserBean.class);
            //新增抽奖资格
            ActDrawNum actDrawNum = new ActDrawNum();
            actDrawNum.setName(userBean.getName());
            actDrawNum.setNowNumber(0);
            actDrawNum.setUid(userBean.getUid());
            actDrawNum.setMaxNumber(1);
            actDrawNumMapper.inputDrawNumber(actDrawNum);
        } catch (DuplicateKeyException e) {
            //已存在用户的抽奖资格则累加抽奖机会
            actDrawNumMapper.updateMaxNumber(userBean.getUid());
        } catch (Exception e1) {
            throw new RuntimeException("消息处理异常：" + e1);
        }
    }
}
